{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4ecf68f5-1b41-4bc3-bee6-9bef4170306e",
   "metadata": {},
   "source": [
    "# 操作CSV文件"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9659554-8926-4c7e-9d32-7a253e5cac04",
   "metadata": {},
   "source": [
    "CSV(Comma Separated Values)通过逗号（实际上也能通过tab等作为分隔符)分隔数据。处理csv的库：\n",
    "\n",
    "- 标准库 csv\n",
    "- pandas\n",
    "\n",
    "通过python标准库 `csv`操作csv文件。该模块的writer函数会返回一个csvwriter对象，通过该对象的writerow或writerows方法就可以将数据写入到CSV文件中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "fa87e360-ea73-47da-866d-cb0a53e9c532",
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "import random\n",
    "\n",
    "with open('csv/scores.csv', 'w', encoding='utf-8') as file:\n",
    "    # 创建csvwriter对象\n",
    "    writer = csv.writer(file)\n",
    "    # writer = csv.writer(file, delimiter='|', quoting=csv.QUOTE_ALL)\n",
    "    # 表头\n",
    "    writer.writerow(['姓名', '语文', '数学', '英语'])\n",
    "    names = ['关羽', '张飞', '赵云', '马超', '黄忠']\n",
    "    for name in names:\n",
    "        scores = [random.randrange(50, 101) for _ in range(3)]\n",
    "        scores.insert(0, name)\n",
    "        # 通过列表写入一行数据\n",
    "        writer.writerow(scores)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dce8787-6c0d-4e7d-bcd7-d7d5289a640d",
   "metadata": {},
   "source": [
    "writer函数，除了传入要写入数据的文件对象外，还可以接受以下参数：\n",
    "\n",
    "- dialect，它表示CSV文件的方言，默认值是excel。\n",
    "- delimiter，指定分隔符（默认是逗号）\n",
    "- quotechar，包围值的字符（默认是双引号）。包围值的字符主要用于当字段中有特殊符号时，通过添加包围值的字符可以避免二义性。\n",
    "- quoting，包围的方式。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b07883d-37d9-4411-b2e1-bf39e03d344a",
   "metadata": {},
   "source": [
    "## 从CSV文件读取数据"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d2af6c5-d851-42d8-920e-fcdeec3ad00b",
   "metadata": {},
   "source": [
    "通过csv模块的reader函数可以创建出csvreader对象，该对象是一个迭代器，可以通过next函数或for-in循环读取到文件中的数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d1545889-2cd9-444b-a852-47da6e578349",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\t姓名,语文,数学,英语\t\n",
      "2\t\n",
      "3\t关羽,79,68,59\t\n",
      "4\t\n",
      "5\t张飞,82,88,63\t\n",
      "6\t\n",
      "7\t赵云,76,52,74\t\n",
      "8\t\n",
      "9\t马超,73,82,93\t\n",
      "10\t\n",
      "11\t黄忠,67,82,96\t\n",
      "12\t\n"
     ]
    }
   ],
   "source": [
    "import csv\n",
    "\n",
    "with open('csv/scores.csv', 'r', encoding='utf-8') as file:\n",
    "    # 创建csvreader对象\n",
    "    reader = csv.reader(file, delimiter='|')\n",
    "    # 遍历每一行数据（包括表头）\n",
    "    for data_list in reader:\n",
    "        print(reader.line_num, end='\\t')\n",
    "        for elem in data_list:\n",
    "            print(elem, end='\\t')\n",
    "        print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cb335bb-c34a-4954-9228-fbb55bc65527",
   "metadata": {},
   "source": [
    "通过notepad打开时，每条数据之间没有空行。\n",
    "\n",
    "```text\n",
    "姓名,语文,数学,英语\n",
    "关羽,79,68,59\n",
    "张飞,82,88,63\n",
    "赵云,76,52,74\n",
    "马超,73,82,93\n",
    "黄忠,67,82,96\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
